package com.jfinal.aceadmin.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;

import com.jfinal.aceadmin.util.VoUtil;
import com.jfinal.aceadmin.vo.MessageVo;
@Repository
public class UserMessageImpl{
	private static ApplicationContext ctx;
	
	public static UserMessageImpl getDAO() {
		if (null == ctx) {
			ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		}
		UserMessageImpl instance =  ctx.getBean(UserMessageImpl.class);
		return instance;
	}
	
	/**
	 * Get user messages
	 * @param userId
	 * @return
	 */
	public List<MessageVo> getMessages(int userId) {
		List<UserMessage> uMessages = UserMessage.dao.findByUserIdAndRead(userId, false);
		List<MessageVo> messageVos = new ArrayList<MessageVo>();
		for(UserMessage uMessage : uMessages){
			MessageVo messageVo = VoUtil.convert(uMessage);
			messageVos.add(messageVo);
		}
		return messageVos;
	}

	/**
	 * add message to user
	 * @param email
	 */
	public void sendMessage(Email email) {
		UserMessage message = new UserMessage();
		message.setUserId(email.getUserId());
		message.setSenderId(email.getSenderId());
		message.setSenderName(email.getSenderName());
		message.setContent(email.getSenderName() + " send you an email.");
		message.setReaded(false);
		message.setCreatedDate(new Date());
		message.save();
	}
}